image

Convert Number into Sort Number Format In PHP (Eg: 1.2K, 15.10M, 20B etc)

There are two ways to convert numbers into short number format in PHP:

  1. Using theandnbsp;number_format()andnbsp;function:andnbsp;Theandnbsp;number_format()andnbsp;function can be used to format numbers with a variety of options, including the number of decimal places, the thousands separator, and the decimal separator.
To convert a number into short number format using the number_format() function, you can use the following code: PHP
$number = 123456789;
$shortNumber = number_format($number, 0, and#39;.and#39;, and#39;and#39;);

echo $shortNumber; // Output: 123.45M
andnbsp; content_copy This will convert the number 123456789 to the short number format 123.45M, where M stands for million.
  1. Using a custom function:andnbsp;You can also write a custom function to convert numbers into short number format. The following is a simple example of a custom function to convert numbers into short number format:
PHP
function shortNumber($number) {
    $abbreviations = [
        and#39;Kand#39; = 1000,
        and#39;Mand#39; = 1000000,
        and#39;Band#39; = 1000000000,
        and#39;Tand#39; = 1000000000000,
    ];

    foreach ($abbreviations as $abbreviation = $value) {
        if ($number = $value) {
            $number = round($number / $value, 1) . $abbreviation;
            break;
        }
    }

    return $number;
}
andnbsp; content_copy To use the shortNumber() function, you can use the following code: PHP
$number = 123456789;

echo shortNumber($number); // Output: 123.45M

content_copy This will convert the number 123456789 to the short number format 123.45M. Which method you choose to use to convert numbers into short number format depends on your specific needs. If you need a simple and straightforward solution, then you can use the number_format() function. If you need more control over the formatting of the short number format, then you can use a custom function.